<template>
  <el-card class="page-card">
    <div class="page-header">
      <h2>待审核商品</h2>
    </div>

    <div class="table-container">
      <el-table :data="list" stripe border>
        <el-table-column prop="id" label="SPU ID" width="90" />
        <el-table-column prop="title" label="标题" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="类目" width="120" />
        <el-table-column prop="merchantId" label="商家ID" width="100" />
        <el-table-column prop="createTime" label="提交时间" width="180" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 0 || row.status === 3"
              size="small"
              type="success"
              @click="approve(row.id)"
            >
              通过
            </el-button>

            <el-button
              v-if="row.status === 2"
              size="small"
              type="success"
            >
              商家下架商品
            </el-button>

            <!-- status=1 ⇒ 只显示“下架” -->
            <el-button
              v-else-if="row.status === 1"
              size="small"
              type="danger"
              @click="reject(row.id)"
            >
              下架
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page="pageNum"
        :page-size="pageSize"
        :total="total"
        @current-change="fetchList"
      />
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPendingSpus, approveSpu, rejectSpu } from '@/api/product'

const list = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

const fetchList = (page = pageNum.value) => {
  pageNum.value = page
  getPendingSpus(pageNum.value, pageSize.value)
    .then(res => {
      console.log(res.data.data)
      const data = res.data.data
      list.value = data.list
      total.value = data.list.length
    })
    .catch(() => ElMessage.error('加载失败'))
}

const approve = id => {
  ElMessageBox.confirm('确认通过此商品？', '提示', { type: 'warning' })
    .then(() => approveSpu(id))
    .then(() => {
      ElMessage.success('已通过')
      fetchList()
    })
}

const reject = id => {
  ElMessageBox.confirm('确认驳回此商品？', '提示', { type: 'warning' })
    .then(() => rejectSpu(id))
    .then(() => {
      ElMessage.error('已驳回')
      fetchList()
    })
}

onMounted(fetchList)
</script>

<style scoped>
.page-card {
  height: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;
}
.page-header {
  margin-bottom: 20px;
}
.page-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}
.table-container {
  flex: 1;
  overflow: auto;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
